# Copyright 2012 Robert Muth
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; version 3
# of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

"""
HocusPocus Plugin "webcam"
"""


# python imports
import logging
import os
import tornado.options
import tornado.web

# local imports
import utils

STREAMER = "/usr/bin/streamer"
COMMAND = STREAMER + " -q -c %s -s 320x240 -o %s"

# ======================================================================

tornado.options.define(
    "webcam_devices",
    default="",
    type=str,
    multiple=True,
    help="webcam_devices: camera devices")

OPTIONS = tornado.options.options

# ======================================================================

class Camera:
    def __init__(self, device, description):
        self.no = device
        self.description = description
        self._device = device

    def GetPicture(self):
        pass


def GetCameras():
    result = []
    for cam in OPTIONS.webcam_devices:
        description, device = cam.split(":")
        result.append(Camera(device, description))
    return result


class Handler(tornado.web.RequestHandler):
    """ Display webcam page"""

    def initialize(self, template_args):
        logging.debug("webcam hander init")
        self._template_args = template_args

    @tornado.web.asynchronous
    def get(self, dummy_p, *dummy_k):
        logging.info("pulse handler request")
        cameras = GetCameras()

        self._template_args["cameras"] = cameras
        self.write(self.render_string("webcam.html", **self._template_args))
        self.finish()


def GetJpeg(camera):
    logging.info("GetJpeg  " + camera)
    filename = "/tmp/hocuspocus%s.jpeg" % camera.replace("/", "-")
    if os.path.exists(filename):
        os.remove(filename)
    cmd = COMMAND % (camera, filename)
    _, _ = utils.RunCommand(cmd.split())
    logging.info("opening")
    try:
        with open(filename, "rb") as fp:
            logging.info("reading")
            data = fp.read()
    except Exception as err:
        print("@@@@@ ERROR" + str(err))

    logging.info("GetJpeg completed %d", len(data))
    return data



class CommandHandler(tornado.web.RequestHandler):
    """ AJAXy request handler"""

    def initialize(self, template_args):
        logging.debug("webcam command handler init")
        self._template_args = template_args
        self._task_pool = self.application.settings.get('task_pool')

    def SendJpeg(self, data):
        logging.info("SendJpeg completed %d", len(data))
        self.set_header("Content-Type", "image/jpeg")
        self.set_header("Content-Length", len(data))
        self.write(data)
        self.finish()

    @tornado.web.asynchronous
    def get(self, dummy_p, *dummy_k):
        command = self.get_argument("command")
        camera = self.get_argument("camera")
        logging.info("webcam command handler request [%s]", command)
        if command == "get_picture":
            # We do this but asynchronously
            # self.SendJpeg(GetJpeg(camera))
            cb = self.async_callback(self.SendJpeg)
            self._task_pool.apply_async(GetJpeg, [camera], callback=cb)
        else:
            logging.error("unknown command [%s]", command)
            self.finish()


def GetHandlers():
    return [(r"/webcam/(.*)", Handler),
            (r"/webcam_command(.*)", CommandHandler),
            ]

def GetDependencies():
    return [STREAMER]

